/*
 *  Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
 */

package com.huawei.petSystemdemo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.huawei.hmf.tasks.Task;
import com.huawei.hms.common.ApiException;
import com.huawei.hms.support.account.AccountAuthManager;
import com.huawei.hms.support.account.request.AccountAuthParams;
import com.huawei.hms.support.account.request.AccountAuthParamsHelper;
import com.huawei.hms.support.account.result.AuthAccount;
import com.huawei.hms.support.account.service.AccountAuthService;
import com.huawei.petSystemdemo.utils.MyRequest;
import com.huawei.petSystemdemo.utils.Request;

import org.jetbrains.annotations.NotNull;

import java.io.DataOutput;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class AuthWithAuthCodeActivity extends Activity implements View.OnClickListener {
    private final String TAG = "Account";
    private TextView textView;

    private AccountAuthService mAuthService;
    private AccountAuthParams mAuthParam;
    private AccountAuthService mAuthManager;
    //login by code
    private static final int REQUEST_SIGN_IN_LOGIN_CODE = 1003;
    public static final int REQUEST_SIGN_IN_LOGIN = 1002;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_huawei_authcode);
        textView = findViewById(R.id.hwid_log_text);


        findViewById(R.id.hwid_signInCode).setOnClickListener(this);
        findViewById(R.id.hwid_signout).setOnClickListener(this);
        findViewById(R.id.cancel_authorization).setOnClickListener(this);

        findViewById(R.id.signInAccess).setOnClickListener(this);
    }
    //用authcode获取AccessToken,登录
    private void signIn() {
        mAuthParam = new AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM)
                .setIdToken()
                .setAccessToken()
                .createParams();
        mAuthManager = AccountAuthManager.getService(AuthWithAuthCodeActivity.this, mAuthParam);
        startActivityForResult(mAuthManager.getSignInIntent(), REQUEST_SIGN_IN_LOGIN);
    }

    private void signInCode() {
        mAuthParam = new AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM)
                .setProfile()
                .setAuthorizationCode()
                .createParams();
        mAuthService = AccountAuthManager.getService(AuthWithAuthCodeActivity.this, mAuthParam);
        startActivityForResult(mAuthService.getSignInIntent(), REQUEST_SIGN_IN_LOGIN_CODE);
    }

    private void signOut() {
        Task<Void> signOutTask = mAuthService.signOut();
        signOutTask.addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Log.i(TAG, "signOut Success");
                textView.setText("signOut sucess----注销成功");
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
                Log.i(TAG, "signOut fail");
                textView.setText("signOut fail----注销失败");
            }
        });
    }

    private void cancelAuthorization() {
        Task<Void> task = mAuthService.cancelAuthorization();
        task.addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Log.i(TAG, "cancelAuthorization success");
                textView.setText("cancelAuthorization sucess----取消授权成功");
            }
        });//
        task.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
                Log.i(TAG, "cancelAuthorization failure：" + e.getClass().getSimpleName());
                textView.setText("cancelAuthorization failure：----取消授权失败" + e.getClass().getSimpleName());
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.hwid_signInCode:
                signInCode();
                break;
            case R.id.hwid_signout:
                signOut();
                break;
            case R.id.cancel_authorization:
                cancelAuthorization();
                break;
            case R.id.signInAccess://得到AccessToken
                signIn();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // Process the sign-in authorization result and obtain an ID token from AuthHuaweiId.
        //处理登录授权结果并从authHuaweid获取ID令牌。
        super.onActivityResult(requestCode, resultCode, data);
        ///////////////////////////////////////
        if (requestCode == REQUEST_SIGN_IN_LOGIN) {
            //login success
            //get user message by parseAuthResultFromIntent
            //登录成功
            //通过parseAuthResultFromIntent获取用户消息
            Task<AuthAccount> authAccountTask = AccountAuthManager.parseAuthResultFromIntent(data);
            if (authAccountTask.isSuccessful()) {
                AuthAccount authAccount = authAccountTask.getResult();
                Log.i(TAG, authAccount.getDisplayName() + " signIn success ");
                Log.i(TAG, "AccessToken: " + authAccount.getAccessToken());
                textView.setText("登录成功：手机号：" + authAccount.getDisplayName() + " OpenId： " + authAccount.getOpenId() + "DisplayName:  " +authAccount.getDisplayName() + "FamilyName:  " +authAccount.getFamilyName() + "getGivenName:  " +authAccount.getGivenName());

                /////////////////////////////////////////

                Map<String,Object> requestBody = new HashMap<>();
                String authcode = authAccount.getAuthorizationCode();//记住最多只能存255个字符！！！所以这里的authcode存不进数据库，不过不影响
                String accesstoken = authAccount.getAccessToken();
                String openid = authAccount.getOpenId();
                String username = getStringRandom(10);
                System.out.println(openid);
                System.out.println("如果未注册，则使用随机生成的用户名：" + username);
                requestBody.put("accesstoken", accesstoken);
                requestBody.put("authcode",authcode);
                requestBody.put("username",username);
                requestBody.put("password","123456");//设置默认密码为123456
                requestBody.put("openid",openid);
                MyRequest.post("/user/registerByOpenid", requestBody, new Callback() {
                            @Override
                            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                                Looper.prepare();//增加部分
                                Toast.makeText(AuthWithAuthCodeActivity.this,"连接出错",Toast.LENGTH_SHORT).show();
                                System.out.println("华为账号注册失败");
                                Looper.prepare();//增加部分
                            }

                            @Override
                            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                                String json = response.body().string();
                                System.out.println(json);
                                JSONObject jsonObject = JSON.parseObject(json);
                                int statusCode = jsonObject.getInteger("statusCode");
                                String errmsg = jsonObject.getString("errMessage");
                                if(statusCode == 400){
                                    Looper.prepare();//增加部分
                                    System.out.println(errmsg+"初始密码为123456");
                                    Toast.makeText(AuthWithAuthCodeActivity.this,errmsg,Toast.LENGTH_SHORT).show();
                                    Looper.loop();//增加部分
                                }
                                if(statusCode == 200){//华为注册成功
                                    Looper.prepare();//增加部分
                                    Toast.makeText(AuthWithAuthCodeActivity.this,"华为账号注册成功，您的账号： " + username + " ,初始密码： 123456 ，返回即可登录",Toast.LENGTH_SHORT).show();
                                    Looper.loop();//增加部分
                                    System.out.println(username);
                                    System.out.println(errmsg+"初始密码为123456");


                                }
                            }
                });
                    /////////////////////////////////////////


            } else {
                Log.i(TAG, "signIn failed: " + ((ApiException) authAccountTask.getException()).getStatusCode());
            }
        }
        //////////////////////////////////////////
        if (requestCode == REQUEST_SIGN_IN_LOGIN_CODE) {
            Task<AuthAccount> authAccountTask = AccountAuthManager.parseAuthResultFromIntent(data);
            if (
                authAccountTask.isSuccessful()) {
                    // The sign-in is successful, and the user's HUAWEI ID information and ID token are obtained.
                    //登录成功，获取用户的华为ID信息和ID令牌。
                    AuthAccount authAccount = authAccountTask.getResult();
                    Log.i(TAG, "Authorization code:" + authAccount.getAuthorizationCode());
                    textView.setText("sign in successfully----授权码获取成功： " + authAccount.getAuthorizationCode());

                        /////////////////////////////////////////
            } else {
                // The sign-in failed. No processing is required. Logs are recorded to facilitate fault locating.
                //登录失败。不需要处理。记录日志以便于故障定位。
                Log.e(TAG, "sign in failed : " +((ApiException)authAccountTask.getException()).getStatusCode());
                textView.setText("sign in failed----登录失败");
            }
        }
    }

    //生成随机用户名，数字和字母组成,
   public String getStringRandom(int length) {
        String val = "";
        Random random = new Random();
        //参数length，表示生成几位随机数
       for(int i = 0; i < length; i++) {
           String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
           //输出字母还是数字
           if( "char".equalsIgnoreCase(charOrNum) ) {
               //输出是大写字母还是小写字母
               int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
               val += (char)(random.nextInt(26) + temp);
           } else if( "num".equalsIgnoreCase(charOrNum) ) {
               val += String.valueOf(random.nextInt(10));
           }
       }
       return val;
    }
}
